package edualuc.game.JogoGalinhaDroid;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import edualuc.game.R;

public class JogoActivity extends Activity implements Runnable, SensorEventListener {
	private Boolean jogando;
	private Partida partida;
	private InterfaceDaPartida interfaceDaPartida;
	public final int quadrosPorSegundo = 30;
	SensorManager sensorManager;
	float CoordX, CoordY, CoordZ;
	int indiceDoVeiculo = 0; // quando for multi-usuario alterar o valor

    @Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		partida = new Partida();
		interfaceDaPartida = new InterfaceDaPartida(this, partida);
        setContentView(interfaceDaPartida);
        
        //setContentView(R.layout.activity_jogo);

		jogando = true;		
		Thread thread = new Thread(this);
		thread.setPriority(Thread.MIN_PRIORITY);
		thread.start();
		
		sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
		sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_GAME);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_jogo, menu);
        return true;
    }
	
	@Override
    public void onDestroy() {
        jogando = false;
    }
	
	public void run() {
		while( jogando && ! partida.acabouTempo()  ) {
			
			try {
				Thread.sleep(Math.round(1000 / quadrosPorSegundo));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			partida.atualizaTudo();
			interfaceDaPartida.postInvalidate();			
		}
	}

	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){

			// assign directions
			CoordX = event.values[0];
			CoordY = event.values[1];
			CoordZ = event.values[2];
			
			if (Math.abs(CoordX) >= 1 || Math.abs(CoordY) >= 1) {
				if (Math.abs(CoordX) > Math.abs(CoordY)) {
					if (Math.abs(CoordX) > 0) {
						partida.veiculoDobrarParaEsquerda(indiceDoVeiculo);
					} else {
						partida.veiculoDobrarParaDireita(indiceDoVeiculo);
					}
				} else {
					if (Math.abs(CoordY) > 0) {
						partida.veiculoDobrarParaBaixo(indiceDoVeiculo);
					} else {
						partida.veiculoDobrarParaCima(indiceDoVeiculo);
					}
				}
			}
		}
	}
	
}
